﻿using JWTAuthServer.Model;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace JWTAuthServer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class FileController : ControllerBase
    {
        [DisableRequestSizeLimit]
        [HttpPost]
        [Route("PostFileDemo")]
        public IActionResult Upload([FromForm] IFormCollection formCollection)
        {
            var files = formCollection.Files; 
            long size = files.Sum(f => f.Length);             
            var Keys = formCollection.Keys;
            string contentRootPath = AppContext.BaseDirectory;
            List<string> filenames = new List<string>();
            foreach (IFormFile formFile in files)
            {
                if (formFile.Length > 0)
                {
                    string fileExt = Path.GetExtension(formFile.FileName);
                    long fileSize = formFile.Length;
                    string newFileName = Guid.NewGuid().ToString() + fileExt;
                    var filePath = contentRootPath + "/fileUpload/";
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    using (var stream = new FileStream(filePath + newFileName, FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                    }
                    filenames.Add(filePath + newFileName);
                }
            }
            return Ok(new TResponse<List<string>>() { message = "上传成功", code = 200,data = filenames });
        }

        [HttpPost]
        [Route("PostFile")]
        public TResponse PostFile([FromForm] IFormCollection formCollection)
        { 
            //string contentRootPath = AppContext.BaseDirectory;
            if (formCollection.ContainsKey("user"))
            {
                var user = formCollection["user"];
                var keyTest = formCollection["keyTest"];
            }
            List<string> filelists = new List<string>();
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

            if(!fileCollection.Any()) return new TResponse<List<string>>() { message = "fail", code = 500 };

            foreach (IFormFile file in fileCollection)
            {
                StreamReader reader = new StreamReader(file.OpenReadStream());
                string content = reader.ReadToEnd();
                string name = file.FileName;
                string filename = @"D:/FileTest/" + name;

                string path = Path.GetDirectoryName(filename)!;
                 
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
                using (FileStream fs = new FileStream(filename, FileMode.Create))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                filelists.Add(filename); 
            }
            return new TResponse<List<string>>() { message = "success", code = 200,data= filelists };
        }


        [HttpGet]
        [Route("GetFileImage")]
        public IActionResult GetFileImage()
        {
            string filename = @"D:/FileTest/7.jpg";
             
            bool isExists = System.IO.File.Exists(filename);
            FileStream fileStream = null;
            if (isExists){
               fileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read);
            }   
            return File(fileStream, "image/png");
        }


        [HttpGet]
        [Route("GetFileList")]
        public IActionResult GetFileList()
        {
            string filename1 = @"D:/FileTest/9.jpg";
            string filename2 = @"D:/FileTest/8.jpg";
            if (!System.IO.File.Exists(filename1))
            {
                return Ok(new TResponse<List<string>>() { message = "文件不存在", code = 400});
            }

            var fbase1=  DocumentToBase64Str(filename1);

             var fbase2 = DocumentToBase64Str(filename2);

            var aa = fbase1.Length;

            List<string> list = new List<string>();
            list.Add(fbase1);
            list.Add(fbase2);

            return Ok(new TResponse<List<string>>() { message = "数据加载成功", code = 200, data = list });
        }


        /// <summary>
        /// 文件 转 base64 
        /// </summary>
        /// <param name="fileName">文件全路径</param>
        /// <returns></returns>
        private string DocumentToBase64Str(string fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.OpenOrCreate);

            byte[] bt = new byte[filestream.Length];
            //调用read读取方法
            filestream.Read(bt, 0, bt.Length);
            string base64Str = Convert.ToBase64String(bt);
            filestream.Close();
            return base64Str;
        } 
    }
}
